﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.IO;

namespace AlphaGet
{
    public class HTTPDownloadProcessor
    {
        private ArrayList _webRequests;
        private int _chunkSize;
        private int _completedChunks = 0;
        public string FileName
        {
            get;
            set;
        }
        public Uri Uri
        {
            get;
            set;
        }
        public int ChunkSize
        {
            get
            {
                return _chunkSize;
            }
        }

        public int CompletedChunks
        {
            get
            {
                return _completedChunks;
            }
        }

        public int ChunksNumber
        {
            get;
            set;
        }

        public long FileSize
        {
            get;
            set;
        }

        public string UserAgent
        {
            get;
            set;
        }

        public HTTPDownloadProcessor(string fileName, int numChunks, Uri url, string userAgent)
        {
            FileName = fileName;
            ChunksNumber = numChunks;
            Uri = url;
            UserAgent = userAgent;

            SendGetFileSizeRequest();

            _chunkSize = (int)Math.Ceiling((decimal)FileSize / (decimal)ChunksNumber);
        }


        private long SendGetFileSizeRequest()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uri);
            req.Method = WebRequestMethods.Http.Head;
            HttpWebResponse resp = (HttpWebResponse)(req.GetResponse());
            FileSize = resp.ContentLength;
            return FileSize;
        }

        public void StartDownload()
        {
            _webRequests = new ArrayList(ChunksNumber);
            for (int i = 0; i < ChunksNumber; i++)
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Uri);
                webRequest.Method = WebRequestMethods.Http.Get;
                webRequest.AddRange(i*ChunkSize, Math.Min((i+1)*ChunkSize-1, FileSize));

                //webRequest.BeginGetRespons 
                _webRequests.Add(webRequest);
            }
        }

        public void ChunkCompleted(int chunkNumber)
        {
            _completedChunks++;
            if (_completedChunks == ChunksNumber)
            {
                //DownloadComplete();
            }
        }
    }
}
